package calculator;


import calculator.proxy.CalcProxy;
import calculator.task.AccumulationTask;
import calculator.task.FibonacciTask;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by liyf on 2015/3/29 0029.
 */
public class CalcServerDispatcher {
    private static CalcServerDispatcher singleton = null;

    private CalcServerDispatcher() {
    }

    public static CalcServerDispatcher instance() {
        if (singleton == null) {
            singleton = new CalcServerDispatcher();
        }
        return singleton;
    }

    public FullHttpResponse route(HttpRequest request) {
        String url;

        Map parameterMap = new HashMap<String, List<String>>();
        if (request.uri().indexOf('?') != -1) {
            url = request.uri().substring(0, request.uri().indexOf('?'));
            QueryStringDecoder decoder = new QueryStringDecoder(request.uri());
            parameterMap = decoder.parameters();
        } else {
            url = request.uri();
        }
        String output;
        CalcProxy<String> calcProxy = new CalcProxy<>();
        switch (url) {
            case "/f":
            case "/fibonacci":
                output = calcProxy.proxy(new FibonacciTask(parameterMap)).calc();
                break;
            case "/a":
            case "/accumulation":
                output = calcProxy.proxy(new AccumulationTask(parameterMap)).calc();
                break;
            default:
                output = "欢迎来到计算器服务器";
                break;
        }
        output = String.format("计算结果:%s\n<br>请求地址:%s\n<br>请求参数:%s", output, url, parameterMap);


        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(output.getBytes()));
        response.headers().set(CONTENT_TYPE, "text/html;charset=UTF-8");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
        return response;
    }
}
